<template>
  <view class="login-wrap" :data-theme="globPrimary">
    <u-navbar :border-bottom="false" :custom-back="onBack"></u-navbar>
    <view class="tabs">
      <view
        class="item"
        :style="{
          color: current == 'user' ? globPrimaryColor : '',
        }"
        @click="handleTabChange('user')"
        v-if="globLoginConfig && globLoginConfig.user"
        >密码登录</view
      >
      <view
        class="item"
        :style="{
          color: current == 'verify' ? globPrimaryColor : '',
        }"
        @click="handleTabChange('verify')"
        v-if="globLoginConfig && globLoginConfig.verify"
        >验证码登录</view
      >
    </view>
    <!-- 验证码登录 -->
    <u-form
      :model="verifyForm"
      ref="verifyForm"
      :error-type="errorType"
      label-width="120rpx"
      v-show="current == 'verify'"
    >
      <u-form-item label="+86" left-icon="arrow-down" prop="phone"
        ><u-input v-model="verifyForm.phone" placeholder="请输入手机号" type="number"
      /></u-form-item>
      <u-form-item label="验证码" prop="verify">
        <u-input placeholder="请输入验证码" v-model="verifyForm.verify" type="text"></u-input>
        <edu-button
          slot="right"
          type="text"
          :disabled="verifyDisabled || codeType"
          @click="handleGetCode"
          class="verify-btn"
          >{{ codeTips }}</edu-button
        >
      </u-form-item>
    </u-form>
    <!-- 账号登录 -->
    <u-form
      :model="userForm"
      ref="userForm"
      :error-type="errorType"
      label-width="58rpx"
      v-show="current == 'user'"
    >
      <u-form-item
        :leftIconStyle="{ color: '#B7BAC1', fontSize: '40rpx' }"
        left-icon="account"
        prop="user"
      >
        <u-input placeholder="请输入账号" v-model="userForm.user" type="text"></u-input>
      </u-form-item>
      <u-form-item
        :leftIconStyle="{ color: '#B7BAC1', fontSize: '40rpx' }"
        left-icon="lock"
        prop="password"
      >
        <u-input
          :password-icon="true"
          type="password"
          v-model="userForm.password"
          placeholder="请输入密码"
        ></u-input>
      </u-form-item>
    </u-form>
    <view class="alternative" :style="{ color: globPrimaryColor }">
      <view @tap="jump('/pageUser/login/forgot')">忘记密码？</view>
      <view @tap="jump('/pageUser/login/register')" class="reg">注册</view>
    </view>
    <edu-button type="primary" @click="handleSubmit">登录</edu-button>

    <!-- #ifdef MP-WEIXIN -->
    <view
      class="wx-login-btn"
      v-if="!$u.test.empty(thirdloginData) && thirdloginData.includes('weixin')"
    >
      <edu-button
        plain
        :hairLine="false"
        type="primary"
        open-type="getPhoneNumber"
        @getphonenumber="onGetPhoneNumber"
      >
        手机号快捷登录
      </edu-button>
    </view>
    <!-- #endif -->

    <!-- #ifdef H5 || APP-PLUS -->
    <view class="bottom" v-if="!$u.test.empty(thirdloginData)">
      <u-divider half-width="50" margin-bottom="60">第三方登录</u-divider>
      <u-row justify="around">
        <u-image
          width="80rpx"
          v-if="Object.keys(thirdloginData).includes('qq')"
          height="80rpx"
          @click="qqLogin"
          src="@/static/images/login_icon_qq.png"
        ></u-image>
        <u-image
          width="80rpx"
          v-if="Object.keys(thirdloginData).includes('weixin')"
          height="80rpx"
          @click="onGetWeChatCode"
          src="@/static/images/login_icon_wechat.png"
        ></u-image>
      </u-row>
    </view>
    <!-- #endif -->

    <u-verification-code
      seconds="60"
      ref="uCode"
      @change="codeChange"
      @end="codeEnd"
      @start="codeStart"
    ></u-verification-code>
    <u-toast ref="uToast" />

    <!-- <privacy-popup @agree="agree" @disagree="disagree"></privacy-popup> -->
  </view>
</template>

<script>
import md5Libs from '@/uview-ui/libs/function/md5'
import setting from '@/settings/projectSetting.js'
// import privacyPopup from '@/components/privacyPopup'
import { mapGetters } from 'vuex'
export default {
  components: {
    // privacyPopup,
  },
  data() {
    return {
      setting,
      current: 'user',
      verifyForm: {
        phone: '',
        verify: '',
      },
      userForm: {
        user: '',
        password: '',
      },
      rulesVerify: {
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['change', 'blur'],
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            trigger: ['change', 'blur'],
          },
        ],
        verify: [
          {
            required: true,
            message: '请输入验证码',
            trigger: ['change', 'blur'],
          },
        ],
      },
      rulesUser: {
        user: [
          {
            required: true,
            message: '请输入账号',
            trigger: ['change', 'blur'],
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['change', 'blur'],
          },
        ],
      },
      codeTips: '',
      codeType: true,
      errorType: ['message'],

      isWeixin: false,
      thirdloginData: {},

      authCode: '', //钉钉code
      access_token: '',
      userid: '',
    }
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      globLoginConfig: 'projectSetting/getGlobLoginConfig',
    }),
    verifyDisabled() {
      let _this = this
      let disabled = true
      if (_this.$u.test.mobile(_this.verifyForm.phone)) {
        _this.codeType = false
        disabled = false
      } else {
        _this.codeType = true
      }
      return disabled
    },
  },
  // 监听页面返回
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    this.onBack()
    return true
  },
  options: {
    styleIsolation: 'shared',
  },
  created() {
    if (this.globLoginConfig) {
      if (this.globLoginConfig.user) {
        this.current = 'user'
      } else if (this.globLoginConfig.verify) {
        this.current = 'verify'
      }
    }
  },
  onShow() {
    uni.hideLoading()
  },
  onLoad() {
    // 当前网页的url，供微信重定向使用
    let query = {}
    /* #ifdef H5 */
    let loc_href = this.setting.appBaseUrl + '/pageUser/setting/wechatLogin'
    query = {
      redirect_uri: loc_href,
    }
    /* #endif */
    this.$edu.api.getConfigThirdlogin(query).then((res) => {
      this.thirdloginData = res.data
    })
    // #ifdef MP-ALIPAY
    // 钉钉登录
    dd.getAuthCode({
      success: (res) => {
        this.authCode = res.authCode
      },
    })

    let _this = this
    dd.httpRequest({
      url: 'https://oapi.dingtalk.com/gettoken?appkey=dingflcsv4bdtzdmmfzp&appsecret=MdHci_uJ5jBlSmiIGTMeh_iDiLajXYKX4QfCwCS1j6JZZOkeqQnQvZe6-xtSHDO6',
      success: (res) => {
        _this.access_token = res.data.access_token
        dd.httpRequest({
          url:
            'https://oapi.dingtalk.com/user/getuserinfo?access_token=' +
            _this.access_token +
            '&code=' +
            _this.authCode,
          success: (res) => {
            _this.userid = res.data.userid
            dd.httpRequest({
              url:
                'https://oapi.dingtalk.com/user/get?access_token=' +
                _this.access_token +
                '&userid=' +
                _this.userid,
              success: (res) => {
                console.log(res)
              },
            })
          },
        })
      },
    })
    // #endif
  },
  methods: {
    handleSubmit() {
      if (this.current == 'verify') {
        this.$refs.verifyForm.validate((valid) => {
          if (valid) {
            this.$edu.api
              .createUserLogin({
                ...this.verifyForm,
                logintype: 'verify',
              })
              .then((res) => {
                const { msg, data } = res
                this.handleLoginSucc(data, msg)
              })
              .catch((err) => {
                this.$u.toast(err.msg)
              })
          }
        })
      } else if (this.current == 'user') {
        this.$refs.userForm.validate((valid) => {
          if (valid) {
            this.$edu.api
              .createUserLogin({
                ...this.userForm,
                password: md5Libs.md5(this.userForm.password),
                logintype: 'user',
              })
              .then((res) => {
                const { msg, data } = res
                this.handleLoginSucc(data, msg)
              })
              .catch((err) => {
                this.$u.toast(err.msg)
              })
          }
        })
      }
    },
    handleLoginSucc(succ, msg) {
      this.$store.commit('user/setToken', succ)
      // 获取个人信息
      this.$store.dispatch('user/setUserInfo', succ)

      // 用户openid
      this.$store.dispatch('projectSetting/setGlobWeixinAppid')
      // 更新购物车数量
      this.$store.dispatch('projectSetting/setGlobCartNumber')
      // 更新未读消息
      this.$store.dispatch('projectSetting/setGlobNotifyUnread')
      this.onBack()

      // 设置用户头像
      this.$store.commit('user/setAvatar', succ.avatar_url)
    },
    // 获取验证码
    handleGetCode() {
      if (this.$refs.uCode.canGetCode) {
        this.$edu.api
          .createVerify({
            phone: this.verifyForm.phone,
            type: 'login',
          })
          .then((res) => {
            const { msg } = res
            this.$u.toast(msg)
            this.$refs.uCode.start()
          })
      }
    },
    // qq登录
    qqLogin() {
      // #ifdef H5
      window.location.replace(this.thirdloginData.qq)
      // #endif

      // #ifdef APP-PLUS
      let that = this
      uni.getProvider({
        service: 'oauth',
        success: function (res) {
          if (~res.provider.indexOf('qq')) {
            uni.showLoading({
              title: '加载中',
            })
            uni.login({
              provider: 'qq',
              success: function (loginRes) {
                let oauth = loginRes.authResult.openid
                that.$edu.api
                  .getAppLogin({
                    type: 'qq',
                    oauth: oauth,
                  })
                  .then((ress) => {
                    const { msg, data } = ress
                    that.handleLoginSucc(data, msg)
                    setTimeout(() => {
                      uni.hideLoading()
                    }, 1000)
                  })
                  .catch(() => {
                    uni.hideToast()
                    uni.$u.route({
                      type: 'redirectTo',
                      url: '/pageUser/setting/wechatLogin',
                      params: {
                        state: 'qq',
                        oauth: oauth,
                      },
                    })
                    setTimeout(() => {
                      uni.hideLoading()
                    }, 1000)
                  })
              },
              fail: function () {
                uni.hideLoading()
              },
            })
          }
        },
      })
      // #endif
    },
    //微信登录
    onGetWeChatCode() {
      // #ifdef H5
      location.href = this.thirdloginData.weixin
      // #endif

      // #ifdef APP-PLUS
      let that = this
      uni.getProvider({
        service: 'oauth',
        success: (res) => {
          if (~res.provider.indexOf('weixin')) {
            uni.showLoading({
              title: '加载中',
            })
            uni.login({
              provider: 'weixin',
              success: (loginRes) => {
                let oauth = loginRes.authResult.openid
                that.$edu.api
                  .getAppLogin({
                    type: 'weixin',
                    oauth: oauth,
                  })
                  .then((ress) => {
                    const { msg, data } = ress
                    that.handleLoginSucc(data, msg)
                    setTimeout(() => {
                      uni.hideLoading()
                    }, 1000)
                  })
                  .catch((err) => {
                    uni.hideToast()
                    uni.$u.route({
                      type: 'redirectTo',
                      url: '/pageUser/setting/wechatLogin',
                      params: {
                        state: 'weixin',
                        oauth: oauth,
                      },
                    })
                    setTimeout(() => {
                      uni.hideLoading()
                    }, 1000)
                  })
              },
              fail: () => {
                uni.hideLoading()
              },
            })
          }
        },
      })
      // #endif
    },
    // 微信小程序获取手机号登录
    onGetPhoneNumber(e) {
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        this.$edu.api
          .setUserLoginMiniapp({
            code: e.detail.code,
          })
          .then((res) => {
            const { msg, data } = res
            this.handleLoginSucc(data, msg)
          })
      }
    },
    // 倒计时
    codeChange(text) {
      this.codeTips = text
    },
    // 倒计时开始
    codeStart() {
      this.codeType = true
    },
    // 倒计时结束
    codeEnd() {
      this.codeType = false
    },
    // tab 跳转
    handleTabChange(key) {
      this.current = key
    },
    // 路由跳转
    jump(path) {
      this.$u.route({
        url: path,
      })
    },
    // 返回上一页
    onBack() {
      let pages = getCurrentPages()
      let page = pages[pages.length - 2]
      let currentPage = pages[pages.length - 1]
      if (this.$u.test.empty(page) || page.route == currentPage.route) {
        this.$u.route({ type: 'switchTab', url: 'pages/user/index' })
      } else {
        this.$u.route({ type: 'back' })
      }
    },
    /* agree(e) {
      console.log('用户同意隐私授权, 接下来可以调用隐私协议中声明的隐私接口')
      uni.getClipboardData({
        success(res) {
          console.log('getClipboardData success', res)
        },
        fail(res) {
          console.log('getClipboardData fail', res)
        },
      })
    },
    disagree(e) {
      console.log('用户拒绝隐私授权, 未同意过的隐私协议中的接口将不能调用')
    }, */
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.verifyForm.setRules(this.rulesVerify)
    this.$refs.userForm.setRules(this.rulesUser)
  },
}
</script>

<style lang="scss" scoped>
.login-wrap {
  padding: 0 95rpx;
  height: calc(100vh);
  /* #ifdef H5 */
  height: calc(100vh - var(--window-top));
  /* #endif */
  background-color: #fff;
  .tabs {
    display: flex;
    margin-bottom: 30rpx;
    .item {
      flex: 1;
      height: 80rpx;
      font-size: 32rpx;
      font-weight: 400;
      color: $edu-tips-color;
      line-height: 80rpx;
      text-align: center;
    }
  }
  /deep/.u-form-item {
    color: #606266;
    .u-form-item--left__content {
      flex-direction: row-reverse;
    }
  }
  .verify-btn {
    margin-left: auto;
  }
  .alternative {
    color: $edu-tips-color;
    font-size: 28rpx;
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
    margin-bottom: 80rpx;
    .reg {
      @include text-color();
    }
  }
  .bottom {
    margin-top: 60rpx;
  }

  .wx-login-btn {
    margin-top: 48rpx;
  }
  .code-disabled {
    color: #b7bac1;
  }
}
</style>
